<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">绩效管理</span>
      <el-button
          type="primary"
          v-if="getUser.level >= 20"
          style="float: right; margin-top: 13px;"
          @click="beforeAddPerformance">
        新增记录
      </el-button>
    </div>

    <!-- 绩效弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form label-width="120px" :model="performanceForm" :rules="rules" ref="performanceForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工" prop="employeeId">
              <el-select
                  v-model="performanceForm.employeeId"
                  placeholder="请选择员工"
                  filterable
                  style="width:100%">
                <el-option
                    v-for="emp in employeeOptions"
                    :key="emp.id"
                    :label="emp.name"
                    :value="emp.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核周期" prop="cycle">
              <el-input
                  v-model="performanceForm.cycle"
                  placeholder="例如：2023-Q3"
                  style="width:100%">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="考核分数" prop="score">
              <el-input-number
                  v-model="performanceForm.score"
                  :min="0"
                  :max="100"
                  :precision="1"
                  style="width:100%">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitPerformance">保存</el-button>
      </template>
    </el-dialog>

    <!-- 绩效查询 -->
    <el-card style="margin: 20px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.employeeName" clearable></el-input>
        </el-form-item>
        <el-form-item label="考核周期">
          <el-input
              v-model="searchForm.cycle"
              placeholder="例如：2023-Q3"
              clearable>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadPerformanceList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
      <!-- 绩效列表 -->
      <el-card style="margin: 20px;">
        <el-table :data="performanceList">
          <el-table-column label="编号" type="index" align="center"></el-table-column>
          <el-table-column prop="name" label="员工姓名" align="center"></el-table-column>
          <el-table-column prop="cycle" label="考核周期" align="center"></el-table-column>
          <el-table-column prop="score" label="考核分数" align="center">
            <template #default="{row}">{{ row.score }}分</template>
          </el-table-column>
          <el-table-column prop="level" label="绩效等级" align="center">
            <template #default="{row}">
              <el-tag :type="getLevelTagType(row.level)">
                {{ formatLevel(row.level) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{row}">
              <el-button link type="text" :disabled="getUser.level < 20" @click="editPerformance(row)">编辑</el-button>
              <el-button link type="text" :disabled="getUser.level < 20" @click="deletePerformance(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.current"
            :page-sizes="[3, 4, 5]"
            :page-size="pagination.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            style="margin-top: 20px;"
        >
        </el-pagination>
      </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';
import qs from "qs";

export default {
  data() {
    return {
      getUser: this.$getUser(),
      dialogVisible: false,
      dialogTitle: '新增绩效记录',
      performanceForm: {
        id: null,
        employeeId: null,
        cycle: '',
        score: 0
      },
      rules: {
        employeeId: [{ required: true, message: '请选择员工', trigger: 'blur' }],
        cycle: [{ required: true, message: '请输入考核周期', trigger: 'blur' }],
        score: [
          { required: true, message: '请输入考核分数', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '分数范围0-100', trigger: 'blur' }
        ]
      },
      searchForm: {
        employeeName: '',
        cycle: ''
      },
      performanceList: [],
      employeeOptions: [],
      pagination: {
        current: 1,
        size: 3,
        total: 0
      }
    };
  },
  mounted() {
    this.loadPerformanceList();
    this.loadEmployees();
  },
  methods: {
    // 加载绩效列表
    loadPerformanceList() {
      const data = qs.stringify({
        pageCurrent: this.pagination.current,
        pageSize: this.pagination.size,
        ...this.searchForm
      });

      axios.get(this.$BASE_URL+'/v1/performance/list?'+data)
          .then(res => {
            if (res.data.state === 2000) {
              this.performanceList = res.data.data.performanceList;
              this.pagination.total = res.data.data.total;
            }
          });
    },

    // 加载员工列表
    loadEmployees() {
      axios.get(this.$BASE_URL+'/v1/user/list')
          .then(res => {
            if (res.data.state === 2000) {
              this.employeeOptions = res.data.data.userList;
            }
          });
    },

    // 格式化等级显示
    formatLevel(level) {
      const map = {
        S: '卓越',
        A: '优秀',
        B: '良好',
        C: '合格',
        D: '待改进'
      };
      return map[level] || level;
    },

    // 获取等级标签样式
    getLevelTagType(level) {
      const types = {
        S: 'success',
        A: 'primary',
        B: '',
        C: 'warning',
        D: 'danger'
      };
      return types[level] || '';
    },

    // 提交绩效数据
    submitPerformance() {
      this.$refs.performanceForm.validate(valid => {
        if (valid) {
          axios.post(this.$BASE_URL+'/v1/performance/save', qs.stringify(this.performanceForm))
              .then(res => {
                if (res.data.state === 2000) {
                  Message.success('保存成功');
                  this.dialogVisible = false;
                  this.loadPerformanceList();
                } else {
                  Message.error(res.data.message);
                }
              });
        }
      });
    },

    // 新增绩效
    beforeAddPerformance() {
      this.dialogTitle = '新增绩效记录';
      this.dialogVisible = true;
      this.performanceForm = {
        id: null,
        employeeId: null,
        cycle: '',
        score: 0
      };
    },

    // 编辑绩效
    editPerformance(row) {
      this.dialogTitle = '编辑绩效记录';
      console.log(row)
      this.performanceForm = {
        id: row.id,
        employeeId: row.employeeId,
        cycle: row.cycle,
        score: row.score
      };
      this.dialogVisible = true;
    },

    // 删除绩效
    deletePerformance(id) {
      this.$confirm('确定删除该绩效记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        axios.post(this.$BASE_URL+`/v1/performance/delete/${id}`)
            .then(res => {
              if (res.data.state === 2000) {
                Message.success('删除成功');
                this.loadPerformanceList();
              } else {
                Message.error(res.data.message);
              }
            });
      });
    },

    // 重置查询
    resetSearch() {
      this.searchForm = {
        employeeName: '',
        cycle: ''
      };
      this.loadPerformanceList();
    },

    // 分页处理
    handleSizeChange(size) {
      this.pagination.size = size;
      this.loadPerformanceList();
    },

    handleCurrentChange(current) {
      this.pagination.current = current;
      this.loadPerformanceList();
    },

    handleClose(){
      this.dialogVisible = false;
      this.$refs.performanceForm.resetFields();
      this.performanceForm = {
        id: null,
        employeeId: null,
        cycle: '',
        score: 0
      };
    }
  }
};
</script>

<style scoped>

</style>